package com.example.layui.service;

import com.example.layui.config.SmsConfig;
import com.example.layui.mapper.OrderMapper;
import com.example.layui.mapper.ProductDao;
import com.example.layui.mapper.ProductMapper;
import com.example.layui.mapper.UserMapper;
import com.example.layui.pojo.Order;
import com.example.layui.pojo.Product;
import com.example.layui.pojo.User;
import com.example.layui.pojo.UserVo;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.annotation.RequestScope;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class ProductServiceImpl implements ProductService {
    @Resource
    ProductMapper productMapper;
    @Resource
    ProductDao productDao;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    UserMapper userMapper;
    @Resource
    OrderMapper orderMapper;
    @Resource
    SmsConfig smsConfig;

    @Override
    public List<Product> getAllProductByPage(int page, int limit) {
        int start = (page - 1) * limit;
        int size = limit;
        return productMapper.getAllProductByPage(start, size);
    }

    @Override
    public List<Product> getAllProduct() {
        return productMapper.getAllProduct();
    }

    @Override
    public int updateProduct(Product product) {
        //修改elasticsearch的数据
        productDao.save(product);
        //修改redis库存
        stringRedisTemplate.opsForValue().set(String.valueOf(product.getId()), String.valueOf(product.getProductStack()));
        //修改数据库数据
        productMapper.updateProduct(product);
        return 0;
    }


    @RabbitHandler
    @RabbitListener(queues = "TestDirectQueue")
    public void process(Order order) {
        //拿到所有帮客
        List<UserVo> bangkeList = userMapper.getALlBangke();
        Random random = new Random();
        int num = random.nextInt(bangkeList.size());
        UserVo bangke = bangkeList.get(num);
        order.setBangkeId(bangke.getId());
        orderMapper.updateBangkeId(order);
        String str = "您的订单数量" + order.getProductNum() + "的" + order.getProductName() + "已被帮客" + bangke.getName() + "接单";
        try {
            smsConfig.send(order.getUserPhone(), "1", new String[]{str, "1"});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
